package com.zhimi.tools.mp3extractor;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.*;

public class SQLiteJDBC {
	public static void main(String args[]) throws Exception {
		
		if (args.length != 4){
			System.out.println("Use the jar as following:");
			System.out.println("mp3extrator.jar databaseFileName tableName nameColumn mp3Column");
			System.exit(0);	
		}
		String dbname = args[0];
		String tbname = args[1];
		String mp3namecolumn = args[2];
		String mp3content = args[3];
		
		
		Class.forName("org.sqlite.JDBC");
		
		//Connection c = DriverManager.getConnection("jdbc:sqlite:voice.db");
		Connection c = DriverManager.getConnection("jdbc:sqlite:" + dbname);
		System.out.println("Opened database successfully");

		Statement stmt = c.createStatement();
		String sql = "select "+ mp3namecolumn + ", "+ mp3content+ " from " + 
				tbname + " ";
		
		System.out.println(sql);

		ResultSet rs = stmt.executeQuery(sql);
		
		String resultFolder = "result_" + dbname.substring(0, dbname.indexOf("."));
		File dir = new File(resultFolder);
		dir.mkdir();
		
		int count = 0;
		while (rs.next()) {
			String filename = rs.getString(mp3namecolumn);
			Object filecontent = rs.getObject(mp3content);
			DataOutputStream out = new DataOutputStream(new FileOutputStream(
					resultFolder + "/" + filename + ".mp3"));
			out.write((byte[]) filecontent);
			count ++;
			System.out.print(".");
		}
		System.out.println(".");
		System.out.println("Finish! Total mp3 count is " + count);
		rs.close();
		stmt.close();
		c.close();

	}
}